package com.jy.modules.cims.common.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.exception.CimsExceptionConstant;
import com.jy.modules.cims.common.exception.SysAssistException;
import com.jy.modules.cims.component.sysAssist.ExportAndImport;
import com.jy.modules.cims.creditright.service.SettleCreditService;
import com.jy.modules.cims.data.dto.CreditDetailDto;
import com.jy.modules.cims.data.dto.CreditDetailQueryDto;
import com.jy.modules.cims.deal.service.DealService;

@Controller
@RequestMapping("export/")
public class ExportController extends CimsBaseController {
	private static final Logger logger = LoggerFactory.getLogger(CimsModelTemplateController.class);

	@Autowired
	@Qualifier("com.jy.modules.cims.deal.service.DealService")
	private DealService dealService;

	@Autowired
	@Qualifier("com.jy.modules.cims.creditright.service.SettleCreditService")
	private SettleCreditService settleCreditService;

	@RequestMapping("/exportSettle")
	public void exportSettle(HttpServletRequest request, HttpServletResponse response, CreditDetailQueryDto dto) throws IOException {
		String settleFlag = this.getParameterString("settleFlag");
		String contractCode = this.getParameterString("contractCode");
		String templateType = this.getParameterString("templateType");
		String dealType = this.getParameterString("dealType");

		List<CreditDetailDto> creditRightList = null;
		Map<String, Object> searchParams = new HashMap<String, Object>();

		try {
			if ("after".equals(settleFlag)) {
				String dealCode = this.getParameterString("dealCode");
				dto.setDealCode(dealCode);
				searchParams.put("dto", dto);
				creditRightList = dealService.getDealDetailByCreditListForExport(searchParams);
			} else {
				dto.setPackageNum(ExportController.ExportUtil.convertCharset(dto.getPackageNum()));
				dto.setDealType(dealType);
				// 设置异常债权类型
				String abnormalSettle = this.getParameterString("abnormalSettle");
				if (abnormalSettle != null && abnormalSettle.length() > 0) {
					String[] types = abnormalSettle.split(",");
					List<String> planStatusList = new ArrayList<String>();
					for (String type : types) {
						planStatusList.add(type);
					}
					dto.setPlanStatusList(planStatusList);
				}
				dto.setTranFlag(true);
				searchParams.put("dto", dto);
				creditRightList = settleCreditService.searchCreditDetailForSettle(searchParams);
			}

		} catch (Exception e) {
			logger.error("获取债权信息异常：", e);
			e.printStackTrace();
		}

		String fileName = "债权列表";
		if (CimsConstant.DEAL_TYPE_CREDIT_SETTLE.equals(templateType)) {
			fileName = "债权结算-债权列表";
		} else if (CimsConstant.DEAL_TYPE_MONTH_BACK.equals(templateType)) {
			fileName = "月还结算-债权列表";
		} else if (CimsConstant.DEAL_TYPE_LOAN_MONTH_BACK.equals(templateType)) {
			fileName = "贷款月还结算-债权列表";
		} else if (CimsConstant.DEAL_TYPE_LOAN_CREDIT_SETTLE.equals(templateType)) {
			fileName = "贷款债权结算-债权列表";
		}

		ExportAndImport<CreditDetailDto> exportAndImport = new ExportAndImport<CreditDetailDto>();
		HSSFWorkbook workbook = exportAndImport.exportExcel(fileName, contractCode, templateType, creditRightList);
		fileName = exportAndImport.fileNameOperation(contractCode, templateType);
		ExportUtil.write(workbook, fileName, response);
	}

	@RequestMapping("/exportImageZip")
	public void exportImageZip(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//String dealCode = this.getParameterString("dealCode");
		
	}

	public static class ExportUtil {
		public static void write(HSSFWorkbook workbook, String fileName, HttpServletResponse response) throws IOException {
			try {
				fileName = ExportUtil.convertCharset(fileName);
				response.setContentType("application/vnd.ms-excel");
				response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
				response.setCharacterEncoding("UTF-8");
				response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1") + ".xls");
				workbook.write(response.getOutputStream());
				response.getOutputStream().flush();
			} catch (Exception e) {
				throw new SysAssistException(CimsExceptionConstant.EXPORT_EXCEL_FAIL + e.getMessage());
			} finally {
				response.getOutputStream().close();
			}
		}

		public static String convertCharset(String fileName) throws UnsupportedEncodingException {
			String result = fileName;
			if (!fileName.equals(new String(fileName.getBytes("UTF-8"), "UTF-8"))) {
				result = new String(fileName.getBytes("ISO-8859-1"), "UTF-8");
			}
			return result;
		}
	}
}
